<template>
  <!-- <div class="admin-cms-form">{{widgetModel}}</div> -->
  <x-border :title="bordetTitle" icon="flaticon-settings" v-if="async" v-loading="loading" ref="xBorder">
    <zk-auto-form @formLoad="formLoad" :serviceConfig="viewModel" @saveForm="saveForm" ref="zkAutoForm"></zk-auto-form>
  </x-border>
</template>

<script>
  import './var.scss'

  import ala from 'ala'
  export default {
    data () {
      return {
        widgetModel: {},
        viewModel: null,
        async: false,
        bordetTitle: '',
        loading: true
      }
    },
    props: {
      widget: {},
      widgetData: {},
      title: {
        default: ''
      }
    },
    mounted () {
      this.init()
    },
    methods: {
      async init () {
        if (this.$route.query.ChannelId !== undefined) {
          var channelResponse = await this.$ala.httpGet('api/Channel/ViewById', { Id: this.$route.query.ChannelId })
          if (channelResponse) {
            this.borderTitle = channelResponse.name
          }
        }
        // this.widgetModel = await this.$ala.themeWidget(this.widget)
        this.bordetTitle = this.title
        // var type = 'ViewArticle'
        // if (this.widgetData.value !== undefined && this.widgetData.value !== null && this.widgetData.value.type !== undefined) {
        //   type = this.widgetData.value.type
        // }
        // if (this.$route.query.ChannelId !== undefined) {
        //   type = this.$route.query.ChannelId
        // }
        var para = {
          type: 'ArticleAutoForm',
          userId: this.$ala.urlId(),
          id: this.$ala.urlId(),
          ...this.$ala.urlToObject()
        }
        var response = await this.$ala.httpGet('api/Auto/Form', para)
        if (response) {
          this.viewModel = response
          this.bordetTitle = this.viewModel.name
          this.viewModel.isCms = true
          this.async = true
        }
      },
      async saveForm (models) {
        models.userId = this.$ala.urlId()
        models.ChannelId = this.$route.query.ChannelId
        // var type
        // if (this.$route.query.ChannelId !== undefined) {
        //   type = this.$route.query.ChannelId
        // }
        let parameter = {
          type: 'ArticleAutoForm',
          userId: this.$ala.urlId(),
          model: JSON.stringify(models)
        }
        var response = await this.$ala.httpPost('api/auto/save', parameter)
        if (response) {
          this.$ala.toMessage(response)
        }
        if (this.$refs.zkAutoForm) {
          this.$refs.zkAutoForm.setSaveStatus(false)
        }
      },
      getPath () {
        this.init().then(() => {
          this.$refs.zkAutoForm.$emit('form_change_widget_data', this.viewModel)
          this.$refs.xBorder.$emit('changeTitle', this.viewModel.name)
        })
      },
      formLoad (val) {
        if (val) {
          this.loading = false
        }
      }
    },
    watch: {
      widgetData: 'getPath'
    }
  }
</script>
